/*
** my_str_to_wordtab.c for my_str_to_wordtab in /home/goupil_r//afs/Jour_08
**
** Made by robin goupil
** Login   <goupil_r@epitech.net>
**
** Started on  Wed Oct 10 13:10:55 2012 robin goupil
** Last update Fri Nov  9 18:05:26 2012 robin goupil
*/

#include <stdlib.h>
#include "my.h"

char	*my_new_word(char **out, int i, int* out_it, int j, char *str)
{
  out[*out_it] = malloc((j + 1) * sizeof(char));
  my_memset(out[*out_it], (j + 1) * sizeof(char), 0);
  my_strncat(out[*out_it], &str[i - j], j);
  out[*out_it] = 0;
  *out_it = *out_it + 1;
  return (out[*out_it]);
}

int	get_word_nbr(char *str, int (*func)(char, char), char sep)
{
  int	i;
  int	cnt;

  i = 0;
  cnt = 0;
  while (str[i] != 0)
    {
      if (func(str[i], sep))
	cnt++;
      i++;
    }
  return (cnt * 8);
}

int	comp_classic(char c, char sep)
{
  return ((my_char_isalpha(c) == 0 && my_char_isnum(c) == 0));
}

int	comp_sep(char c, char sep)
{
  return (c == sep);
}

char    **my_str_to_wordtab(char *str)
{
  int   i;
  int   j;
  int   k;
  char **out;

  i = 0;
  j = 0;
  k = 0;
  out = malloc(get_word_nbr(str, comp_classic, 0) * sizeof(char) + 1);
  while (str[i] != '\0')
    {
      if ((my_char_isalpha(str[i]) == 0 && my_char_isnum(str[i]) == 0))
        {
	  str[i] = '\0';
          if (my_char_isalpha(str[i - k]) == 1 || my_char_isnum(str[i - k]) == 1)
	    my_new_word(out, i, &j, k, str);
          k = (-1);
        }
      i = i + 1;
      k = k + 1;
    }
  if (str[i - k] != '\0')
    my_new_word(out, i, &j, k, str);
  out[j] = '\0';
  return (out);
}

char		*my_new_sep_word(char **out, int i, int j, char *str)
{
  *out = xmalloc(j * sizeof(char) + 1);
  my_memset(*out, j * sizeof(char) + 1, 0);
  *out = my_strncat(*out, &(str[i - j]), j);
  return (*out);
}

char    **my_str_to_wordtab_sep(char *str, char sep)
{
  char **out;
  int	i;
  int	j;
  int	out_it;

  i = 0;
  j = 0;
  out_it = 0;
  out = malloc(get_word_nbr(str, comp_sep, sep) * sizeof(char) + 1);
  while (str[i] != '\0')
    {
      if (str[i] == sep)
        {
	  out[out_it] = my_new_sep_word(&(out[out_it]), i, j, str);
	  out_it++;
          j = (-1);
        }
      i = i + 1;
      j = j + 1;
    }
  out[out_it] = my_new_sep_word(&(out[out_it]), i, j, str);
  out[++out_it] = 0;
  return (out);
}
